<template>
  <div style="height: 100%">
    <AHMF
      :asideWidth="300"
      :rightTitleShow="false"
      :AShow="true"
      leftTitle="模板名称"
    >
      <template #aside>
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          highlight-current
          node-key="id"
          ref="tree"
          v-loading="treeLoading"
        ></el-tree>
      </template>
      <template #header>
        <topSearcher
          :searchOptions="searchOptions"
          @onQuery="onQuery"
          @onReset="onReset"
          :border="false"
        ></topSearcher>
      </template>
      <template #main>
        <div style="margin-bottom: 10px; display: flex">
          <!-- <el-button
            type="primary"
            size="small"
            @click="handleFn('add', currentRow)"
            >新增</el-button
          > -->
          <el-button type="danger" size="small" @click="batchDel"
            >批量删除</el-button
          >
          <el-button type="primary" size="small" @click="batchEdit"
            >批量编辑</el-button
          >
        </div>

        <ETable
          v-loading="tableLoading"
          :data="tableData"
          :titleObj="tableColumns"
          operateWidth="100"
          @sortFun="sortFun"
          :checked="true"
          @batch="batchFn"
          :selectable="checkSelectable"
        >
          <template v-slot="{ scope }">
            <el-button
              @click="handleFn('edit', Object.assign(currentRow, scope))"
              type="text"
              size="small"
              >修改</el-button
            >

            <el-button
              v-if="scope.id"
              @click="delFn(scope)"
              type="text"
              size="small"
              style="color: red"
              >删除</el-button
            >
          </template>
        </ETable>
      </template>
      <template #footer>
        <div class="flex">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.currPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
          >
          </el-pagination>
        </div>
      </template>
    </AHMF>
    <batch_edit ref="batch_edit" @refresh="getTableData"></batch_edit>
    <add_edit_dialog
      ref="add_edit_dialog"
      @refresh="getTableData"
    ></add_edit_dialog>
  </div>
</template>
<script>
import topSearcher from "@/components/topSearcher/topSearcher.vue";
import AHMF from "@/components/topSearcher/AHMF.vue";
import ETable from "@/components/ETable";
import add_edit_dialog from "./components/add_edit_dialog.vue";
import batch_edit from "./components/batch_edit.vue";
import { convertToTreeData } from "@/utils/publicReq.js";
import { BsFormulaApi, deleteBsFormulaByIds } from "@/api/formulaConfig";
import { BsTemplateByIdApi } from "@/api/templateManage";

export default {
  components: {
    AHMF,
    topSearcher,
    ETable,
    add_edit_dialog,
    batch_edit,
  },

  data() {
    return {
      tableLoading: false,
      treeLoading: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },

      //表格字段
      tableColumns: [
        {
          prop: "subjectSign",
          label: "科目标识",
        },
        {
          prop: "isDynamic",
          label: "科目类型",
        },
        // { prop: "subjectName", label: "科目名称" },
        { prop: "subjectRowName", label: "科目行名称" },
        { prop: "subjectColName", label: "科目列名称" },

        { prop: "formula", label: "科目公式" },
        { prop: "asyncFormula", label: "动态公式" },
        { prop: "crTime", label: "创建时间", sortable: "custom" },
      ],
      // 搜索字段
      searchOptions: [
        {
          type: "input",
          label: "科目标识",
          key: "subjectSign",
          value: "",
        },
        {
          type: "select",
          label: "编辑状态",
          key: "isEditor",
          options: [
            { label: "全部", value: "" },
            { label: "未编辑", value: 0 },
            { label: "已编辑", value: 1 },
          ],
          value: "",
        },
      ],
      tableHeight: "随便设置的字符串，只要是字符串，表格高度就会受控于外部样式",
      searchForm: {},
      tableData: [],
      pageInfo: {
        currPage: 1,
        pageSize: 10,
        total: 0,
      },
      batchData: [],
      batchDataIds: [],
      spreadsheetData: [],
      currentRow: {
        excelJson: null,
        templateCode: "",
        templateId: "",
      },
    };
  },
  async created() {},
  async mounted() {
    this.tableLoading = true;
    this.treeLoading = true;
    this.treeData = await convertToTreeData();
    this.treeLoading = false;
    if (this.treeData.length !== 0) {
      // 假设每个节点都有一个唯一的id作为node-key
      this.$nextTick(() => {
        setTimeout(async () => {
          this.$refs.tree.setCurrentNode(this.treeData[0]);
          await this.handleNodeClick(this.treeData[0]);
        });
      });
    }
  },
  methods: {
    // 判断行是否可选
    checkSelectable(row) {
      // 检查id是否存在且不为空
      return row.id !== undefined && row.id !== null && row.id !== "";
    },

    //新增/编辑
    handleFn(type, row) {
      // if (row.excelJson == null) {
      //   this.$message.warning(`请先上传‘${row.templateName}’模板文件`);
      //   return;
      // }
      this.$refs.add_edit_dialog.openFn(type, row);
    },
    batchEdit() {
      //如果未选择模板提示
      if (!this.$refs.tree.getCurrentKey()) {
        this.$message.warning("请选择左侧要批量编辑的模板");
        return;
      }
      this.$refs.batch_edit.openFn(this.currentRow);
    },
    async delFn(scope) {
      let t = await this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let res = await deleteBsFormulaByIds(scope.id);
        if (res.data && res.data.bcode == 0) {
          // 页数大于一页并且当前页只有一条数据，删除后页数-1
          if (
            this.pageInfo.total % this.pageInfo.pageSize === 1 &&
            this.pageInfo.currPage > 1
          ) {
            this.pageInfo.currPage -= 1;
          }
          this.$message.success(res.data.bmsg || "删除成功");
          this.onQuery();
        }
      }
    },
    async batchDel() {
      if (this.batchData.length == 0) {
        this.$message.warning("请选择要删除的数据");
        return;
      }
      let ids = this.batchDataIds.join(",");
      console.log("batchData", ids);
      let t = await this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let res = await deleteBsFormulaByIds(ids);
        if (res.data && res.data.bcode == 0) {
          // 页数大于一页并且当前页只有一条数据，删除后页数-1
          if (
            this.pageInfo.total % this.pageInfo.pageSize === 1 &&
            this.pageInfo.currPage > 1
          ) {
            this.pageInfo.currPage -= 1;
          }
          this.$message.success(res.data.bmsg || "删除成功");
          setTimeout(() => {
            this.onQuery();
          });
        }
      }
    },
    batchFn(data) {
      this.batchData = data;
      this.batchDataIds = data.map((item) => item.id);
    },
    async sortFun(str) {
      this.searchForm.sortStr = str;
      this.getTableData();
    },

    // 获取表格数据
    async getTableData() {
      if (!this.searchForm.templateId) {
        this.tableLoading = false;
        return;
      }
      this.tableLoading = true;
      // 没有排序条件
      let obj = Object.assign(
        {
          currPage: this.pageInfo.currPage,
          pageSize: this.pageInfo.pageSize,
        },
        this.searchForm
      );
      let res = await BsFormulaApi(obj);
      if (res.data && res.data.bdata.total > 0) {
        this.tableData = res.data.bdata.gdata;
        if (this.tableData && this.tableData.length > 0) {
          this.tableData.forEach((item) => {
            item.isDynamic = item.isDynamic == 0 ? "静态" : "动态";
          });
        } else {
          this.tableData = [];
        }
        this.pageInfo.total = res.data.bdata.total;
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.tableLoading = false;
    },
    onReset(searchForm) {
      console.log("重置", searchForm);
      // this.searchForm = searchForm;
      this.pageInfo.currPage = 1;
      this.onQuery(searchForm);
    },
    onQuery(searchForm) {
      console.log("查询", searchForm);
      Object.assign(this.searchForm, searchForm);
      // this.searchForm = searchForm;
      this.getTableData();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageInfo.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageInfo.currPage = val;
      this.getTableData();
    },
    onSubmit() {
      console.log("submit!");
    },
    //树节点选中
    async handleNodeClick(data) {
      console.log(data);

      this.searchForm.templateId = data.id;

      //获取模板数据给新增科目用
      let res = await BsTemplateByIdApi(data.id);
      if (res.data && res.data.bdata && res.data.bcode == 0) {
        // this.currentRow = res.data.bdata;
        this.currentRow.templateId = res.data.bdata.id;
        this.currentRow.templateCode = res.data.bdata.templateCode;
        this.currentRow.excelJson = res.data.bdata.excelJson;
        this.currentRow.templateName = res.data.bdata.templateName;
      } else {
        this.currentRow = {
          templateId: "",
          templateCode: "",
          excelJson: "",
          templateName: "",
        };
      }
      // console.log("currentRow", res.data.bdata, this.currentRow);
      this.pageInfo.currPage = 1;
      this.getTableData();
    },

    //树节点筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>
<style lang="scss" scope></style>
